package com.dldata.devtools30.utils.dataexport;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class DataExportUtil {

    private DataSource dataSource;



    private boolean seeid =false;


    public static DataExportUtil createDataExportUtil(DataSource dataSource,boolean _seeid){
        DataExportUtil dataExportUtil=new DataExportUtil();
        dataExportUtil.dataSource=dataSource;
        dataExportUtil.seeid = _seeid;
        return dataExportUtil;
    }
    
    /**
     * tableConfig导出表配置，
     * @param tableConfigList 导出表列表
     * @param dataMap  顶级表的 需要导出的数据
     * @param nodeletesqlTableName 不需要执行删除语句的表
     * @return
     */
    public String exportData(List<TableConfig> tableConfigList, HashMap<String,List<Object>> dataMap,List<String> nodeletesqlTableName){

        StringBuilder stringBuilder=new StringBuilder();
        for (int i = 0; i < tableConfigList.size(); i++) {
            TableConfig tableConfig = tableConfigList.get(i);
            List<Object> datakeys=dataMap.get(tableConfig.getTablename()); //写死 前面只能是
            for (int j = 0; j < datakeys.size(); j++) {
                Object datakey = datakeys.get(j);
                stringBuilder.append("-- ");
                stringBuilder.append(datakey);
                stringBuilder.append("\r\n");

                stringBuilder.append(getTableData( datakey,tableConfig,nodeletesqlTableName));
            }
        }

        return stringBuilder.toString();
    }

    private StringBuilder getTableData(Object datakey, TableConfig tableConfig,List<String> nodeletesqlTableName) {
        StringBuilder stringBuilder=new StringBuilder();

        boolean isNumber = JdbcDataAccess.getJdbcDataAcess(dataSource).tableFiledIsNumber(tableConfig.getFieldname(), tableConfig.getTablename());
        String conditionsql=datakey==null?(" where "+tableConfig.getFieldname()+ " is null "):(" where "+tableConfig.getFieldname()+" = "+(isNumber?datakey.toString():"'"+datakey+"'"));
        String sql="select * from "+tableConfig.getTablename()+conditionsql;
        List<Map<String,Object>>   hashMapList = JdbcDataAccess.getJdbcDataAcess(dataSource).dbsearch(sql);

        stringBuilder.append("-- ");
        stringBuilder.append(tableConfig.getTablenameZh());
        stringBuilder.append("\r\n");
       if( !nodeletesqlTableName.contains(tableConfig.getTablename()))
        {
            if (tableConfig.getSqldel().equals("true")) {
                stringBuilder.append(" delete from ").append(tableConfig.getTablename()).append(conditionsql);
                stringBuilder.append("\r\n");
            }
            stringBuilder.append(getOneTableData(tableConfig.getTablename(), hashMapList));
        }

        List<TableConfig> subtableList=
                tableConfig.getSubtableList()==null?new LinkedList<>():tableConfig.getSubtableList();
        for (int i = 0; i < subtableList.size(); i++) {
            TableConfig subTableConfig = subtableList.get(i);
            for (int k = 0; k < hashMapList.size(); k++) {
                Map<String, Object> stringObjectHashMap = hashMapList.get(k);
                StringBuilder tablesql=getTableData(stringObjectHashMap.get(subTableConfig.getFfieldname()),subTableConfig, nodeletesqlTableName);
                stringBuilder.append(tablesql);
            }
        }
        return stringBuilder;
    }

    private StringBuilder getOneTableData(String tableName, List<Map<String,Object>> hashMapList) {
        StringBuilder stringBuilder=new StringBuilder();
        hashMapList.forEach(
                hashMap -> {
                    StringBuilder fields=new StringBuilder();
                    StringBuilder values=new StringBuilder();
                    hashMap.entrySet().forEach(
                        stringObjectEntry -> {
                            fields.append(stringObjectEntry.getKey()).append(",");
                            if (seeid && stringObjectEntry.getKey().toLowerCase().equals("id"))
                                stringBuilder.append("-- id:"+stringObjectEntry.getValue()+"\r\n");
                            values.append(stringObjectEntry.getValue()==null?"NULL":(stringObjectEntry.getValue() instanceof String?("'"+((String) stringObjectEntry.getValue()).replaceAll("'","''")+"'"):stringObjectEntry.getValue().toString())).append(",");
                        }
                    );
                    fields.deleteCharAt(fields.length()-1);
                    values.deleteCharAt(values.length()-1);

                    stringBuilder.append(" insert into ").append(tableName);
                    stringBuilder.append(" (").append(fields).append(") ");
                    stringBuilder.append(" values ");
                    stringBuilder.append(" (").append(values).append(")\r\n");
                }
        );
        return stringBuilder;
    }

}
